import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Popconfirm,
  Divider,
  Button,
  Input,
  Drawer,
  Space,
  Table,
  Modal,
  message,
  TreeSelect,
  Form,
  Row,
  Col,
  Tabs,
  Checkbox,
  Menu,
  Dropdown,
  Typography,
} from 'antd';
import { connect } from 'umi';
import { DownOutlined, PlusOutlined, RightOutlined, SyncOutlined } from '@ant-design/icons';
import ProductEdit from './components/productEdit';
import Categories from '../admin/categories';
import { FormInstance } from 'antd/lib/form';
import moment from 'moment';

const { Paragraph } = Typography;
const currControl = 'Edu_Product';

const { TabPane } = Tabs;
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      dataSource: [],
      visible: false,
      selectedRowKeys: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      record: {},
      cascaderOption: [],
      stateKey: '0',
      categoryId: null,
      title: '',
      prdType: '',
      isShelf: '3',
    };
  }

  formRef = React.createRef<FormInstance>();
  componentDidMount() {
    this.fetchDatas(0);
    this.fetchCategory();
  }
  fetchDatas = (t: number) => {
    this.setState({ loading: true });
    let { pageIndex, pageSize, categoryId, title, prdType, isShelf } = this.state;
    if (categoryId == null) {
      categoryId = 0;
    }
    if (t > 0) {
      this.setState({ title: '', categoryId: null });
    }
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: {
          SkipCount: (pageIndex - 1) * pageSize,
          MaxResultCount: pageSize,
          title,
          categoryId,
          prdType,
          isShelf,
        },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.result) {
          var dataSource = resp.result.items;
          this.setState({ loading: false, dataSource, totalCount: resp.result.totalCount });
        }
      });
  };
  //产品分类数据
  fetchCategory = () => {
    this.props
      .dispatch({
        type: 'Category/getTreeData',
        payload: { layout: 'product' },
      })
      .then(() => {
        this.setState({ cascaderOption: this.props.Category.response.result });
      });
  };
  //删除产品
  handleDelete = (id: number) => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { id },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('删除成功！');
          this.fetchDatas(0);
        } else {
          message.error('删除错误，请联系管理员！');
        }
      });
  };
  onCateSelChange = (value: any) => {
    this.setState({ categoryId: value });
  };
  onSelectChange = (selectedRowKeys: any) => {
    this.setState({ selectedRowKeys });
  };
  onSearch = (value: any) => {
    this.setState({ title: value.title }, () => {
      this.fetchDatas(0);
    });
  };
  openModal = (record: any, layout: string) => {
    this.setState({ visible2: true, disabled: true, record, layout });
  };
  closeModal = () => {
    this.setState({ visible2: false });
  };
  swithDrawer = (visible: boolean, record = null) => {
    this.setState({ visible, record });
  };
  refresh = () => {
    this.formRef.current!.resetFields();
    this.setState({ stateKey: '0', prdType: '', isShelf: '3', title: '', categoryId: 0 }, () =>
      this.fetchDatas(1),
    );
  };
  /**控制Tab切换 */
  callback = (key: any) => {
    let state: number = parseInt(key);
    if (state == 0) {
      this.setState({ pageIndex: 1, prdType: '', isShelf: '3' }, () => this.fetchDatas(0));
    } else if (state == 1) {
      this.setState({ pageIndex: 1, prdType: '系列产品', isShelf: '3' }, () => this.fetchDatas(0));
    } else if (state == 2) {
      this.setState({ pageIndex: 1, prdType: '单个产品', isShelf: '3' }, () => this.fetchDatas(0));
    } else if (state == 3) {
      this.setState({ pageIndex: 1, isShelf: '1', prdType: '' }, () => this.fetchDatas(0));
    } else if (state == 4) {
      this.setState({ pageIndex: 1, isShelf: '0', prdType: '' }, () => this.fetchDatas(0));
    }
    this.setState({ stateKey: state });
  };
  //单个操作是否上架
  handleAct = (id: any, act: any) => {
    if (act == 'isShelf') {
      this.props
        .dispatch({
          type: 'Abp/batchShelf',
          payload: { ids: id },
        })
        .then(() => {
          var resp = this.props.response;
          if (resp && resp.success) {
            message.info('执行成功！');
            this.fetchDatas(1);
          }
        });
    }
    if (act == 'isDelete') {
      this.props
        .dispatch({
          type: 'Abp/batchDelete',
          payload: { id },
        })
        .then(() => {
          var resp = this.props.response;
          if (resp && resp.success) {
            message.info('执行成功！');
            this.fetchDatas(1);
          }
        });
    }
  };
  //批量操作是否上架
  handleMenuClick = (e: any) => {
    this.handleAction(e.key);
  };
  handleAction = (act: string) => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length <= 0) {
      message.warning('请至少选择一项！');
      return;
    }
    if (act === 'isShelf') {
      this.props
        .dispatch({
          type: 'Abp/batchShelf',
          payload: { ids: selectedRowKeys.join(',') },
        })
        .then(() => {
          var resp = this.props.response;
          if (resp && resp.success) {
            message.info('执行成功！');
            this.fetchDatas(1);
          }
        });
    } else if (act == 'isDelete') {
      this.props
        .dispatch({
          type: 'Abp/batchDelete',
          payload: { id: selectedRowKeys.join(',') },
        })
        .then(() => {
          var resp = this.props.response;
          if (resp && resp.success) {
            message.info('执行成功！');
            this.fetchDatas(1);
          }
        });
    }
  };
  //分页
  handlePageChange = (pageNumber: any, pageSize: any) => {
    this.setState(
      {
        pageIndex: pageNumber,
        pageSize,
      },
      () => this.fetchDatas(0),
    );
  };

  render() {
    const {
      loading,
      dataSource,
      selectedRowKeys,
      totalCount,
      pageSize,
      categoryId,
      cascaderOption,
      title,
      record,
      stateKey,
      pageIndex,
    } = this.state;
    let parentData = {
      record,
      stateKey,
      title,
      categoryId,
    };
    const columns: any = [
      {
        title: '序号',
        width: 60,
        align: 'center',
        key: 'index',
        render: (_: any, __: any, i: any) => {
          return i + 1;
        },
      },
      {
        title: '产品名称',
        dataIndex: 'title',
        width: 380,
        ellipsis: true,
        render: (text: string, record: any) => (
          <>
            {
              <Paragraph
                copyable={{
                  tooltips: '复制链接',
                  text: `/pages/education/detail?productId=${record.id}&type=3&cateid=1237`,
                }}
              >
                {text}
              </Paragraph>
            }
          </>
        ),
      },
      {
        title: '单价',
        width: 120,
        dataIndex: 'price',
      },
      {
        title: '产品类型',
        width: 150,
        dataIndex: 'prdType',
      },
      {
        title: '排序号',
        width: 120,
        dataIndex: 'sortNum',
      },
      {
        title: '是否上架',
        width: 120,
        dataIndex: 'isShelf',
        render: (text: boolean, record: any) => (
          <Checkbox checked={text} onChange={() => this.handleAct(record.id, 'isShelf')} />
        ),
      },
      {
        title: '创建时间',
        width: 200,
        dataIndex: 'creationTime',
        render: (text: string) => <span>{moment(text).format('YYYY-MM-DD hh:mm:ss')}</span>,
      },
      {
        title: '操作',
        render: (record: any) =>
          dataSource.length >= 1 ? (
            <span>
              <Popconfirm title="确定删除?" onConfirm={() => this.handleAct(record.id, 'isDelete')}>
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical" />
              <a onClick={() => this.swithDrawer(true, record)}>编辑</a>
            </span>
          ) : null,
      },
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        <Menu.Item key="isShelf" icon={<RightOutlined />}>
          是否上架
        </Menu.Item>
        <Menu.Item key="isDelete" icon={<RightOutlined />}>
          批量删除
        </Menu.Item>
      </Menu>
    );
    return (
      <PageHeaderWrapper title={false}>
        <Card>
          <Space>
            <Button
              type="primary"
              onClick={() => this.refresh()}
              loading={loading}
              icon={<SyncOutlined />}
            >
              刷新
            </Button>
            <Dropdown overlay={menu}>
              <Button>
                操作 <DownOutlined />
              </Button>
            </Dropdown>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => this.swithDrawer(true)}>
              新增
            </Button>
            <Button icon={<PlusOutlined />} onClick={() => this.openModal(null, 'product')}>
              产品分类
            </Button>
            <TreeSelect
              allowClear
              style={{ width: 210 }}
              value={categoryId}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={cascaderOption}
              placeholder="请选择分类"
              treeDefaultExpandAll
              onChange={this.onCateSelChange}
            />
            <Form ref={this.formRef} onFinish={this.onSearch} style={{ height: 32 }}>
              <Row>
                <Col span={14}>
                  <Form.Item name="title">
                    <Input placeholder="输入关键词搜索" allowClear />
                  </Form.Item>
                </Col>
                <Col span={4}>
                  <Form.Item>
                    <Button
                      type="primary"
                      // icon={<SearchOutlined />}
                      htmlType="submit"
                      title="查询"
                      style={{ zIndex: 3 }}
                    >
                      搜索
                    </Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Space>
        </Card>
        <Card>
          <Tabs defaultActiveKey={stateKey} onChange={this.callback}>
            <TabPane tab={'全部'} key="0"></TabPane>
            <TabPane tab={'系列产品'} key="1"></TabPane>
            <TabPane tab={'单品'} key="2"></TabPane>
            <TabPane tab={'已上架'} key="3"></TabPane>
            <TabPane tab={'未上架'} key="4"></TabPane>
          </Tabs>
          <Table
            rowKey="id"
            loading={loading}
            rowSelection={rowSelection}
            columns={columns}
            dataSource={dataSource}
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              current: Number(pageIndex),
              pageSize: Number(pageSize),
              onChange: this.handlePageChange,
              pageSizeOptions: ['10', '50', '100', '5000'],
              total: totalCount,
              showTotal: (totalCount) => `总计${totalCount}条数据`,
            }}
          />
        </Card>
        <Drawer
          width={900}
          placement="right"
          closable={false}
          onClose={() => this.swithDrawer(false)}
          visible={this.state.visible}
          destroyOnClose={true}
        >
          <ProductEdit ParentData={parentData} fetchDatas={this.fetchDatas} />
        </Drawer>
        <Modal
          title="产品分类"
          visible={this.state.visible2}
          destroyOnClose={true}
          onCancel={this.closeModal}
          width={700}
          footer={false}
        >
          <Categories layout={this.state.layout} size="small" />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(ViewPage);
